package com.aiit.service.impl;

import com.aiit.entity.TeaOrder;
import com.aiit.mapper.GoodsMapper;
import com.aiit.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
@Slf4j
public class RepoetServiceImpl implements ReportService {

    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 导出运营数据报表
     *
     * @param id
     */
    public void exportBusinessData(Long id) {
        // 查询概览数据
        TeaOrder teaOrder = goodsMapper.findByGoodId(id);
        if (teaOrder == null) {
            log.error("未查询到对应的 TeaOrder 数据，id: {}", id);
            return;
        }
        // 通过POI将数据写入到excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/发票2.xlsx");
        if (in == null) {
            log.error("未获取到发票.xlsx的输入流，检查文件路径及是否在类路径下");
            return;
        }
        log.info("成功获取到发票.xlsx的输入流");


        try {
            // 基于模板文件创建一个新的excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            // 获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            // 获取第8行
            XSSFRow row = sheet.getRow(7);


            row.getCell(0).setCellValue(teaOrder.getProductName());
            row.getCell(2).setCellValue("50");
            row.getCell(4).setCellValue("g");
            row.getCell(5).setCellValue(teaOrder.getQuantity());
            row.getCell(9).setCellValue(teaOrder.getQuantity() * teaOrder.getPrice());
            row.getCell(6).setCellValue(teaOrder.getPrice());
            row.getCell(12).setCellValue(teaOrder.getPrice() * teaOrder.getQuantity());


            // 获取第 9 行
            row = sheet.getRow(8);
            row.getCell(12).setCellValue(teaOrder.getPrice() * teaOrder.getQuantity() + teaOrder.getPrice() * 0.06);


            // 定义输出文件路径
            String outputPath = "G:\\Tea House Graduation Design\\tea-house\\tea-server\\src\\main\\resources\\template\\发票打印\\Sheet2.xlsx";

            // 创建文件输出流
            FileOutputStream out = new FileOutputStream(outputPath);

            // 将Excel文件写入到本地磁盘
            excel.write(out);
            System.out.println("成功");

            // 关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


